<template>
  <div v-loading="loading" v-if="drawerVisible">
    <el-drawer
      v-model="drawerVisible"
      :title="drawerTitle"
      direction="rtl"
      size="80%"
      class="script"
    >
      <operation
        :tabData="{ info, response }"
        @debug="handleDebug"
        @query-com-value="handleQueryValue"
        @open-env="updateEnv"
      />
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import * as DebugApi from '@/api/debug'
import operation from '../../debug/module/operation.vue'
import { useAppStore } from '@/store/modules/app'
import { useDebugStore } from '@/store/modules/debug'
import { isValidDateTime } from '@/utils/dateUtil'
const drawerVisible = ref(false)
const drawerTitle = ref('自定义请求')
const loading = ref(false)
const emit = defineEmits(['success', 'open-env'])
provide('isShowSaveInterfaceBtn', false)
const debugStore = useDebugStore()
const appStore = useAppStore()
let projectId = computed(() => appStore.getSelectProject)
const environmentId = computed(() => debugStore.getEnvironmentId)
const info = ref({} as any)
const queryInfo = ref({} as any)
const response = ref({} as any)
/** 打开弹窗 */
const open = async (row?: any) => {
  await getNodeInfo(row)
  drawerVisible.value = true
  drawerTitle.value = row ? row.name : '自定义请求'
  reset()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const reset = () => {}
/** 打开环境设置弹窗 */
const updateEnv = () => {
  emit('open-env')
}
/** 获取接口、用例详情 */
const getNodeInfo = async (data) => {
  loading.value = true
  try {
    if (!['接口', '用例'].includes(data.tag)) return
    // 判断页签是否存在，存在则定位，否则新增
    let interfaceInfo = {} as any,
      caseInfo = {} as any,
      interfacePostList = []
    // 接口详情
    if (data.tag == '接口') {
      interfaceInfo = await DebugApi.getApiInfo({
        id: data.config ? JSON.parse(data.config).source.id : data.id
      })
      interfacePostList = await DebugApi.getPostProcessorList({
        id: data.config ? JSON.parse(data.config).source.id : data.id
      })
    } else {
      // 接口、用例详情（请求接口详情为获取url、请求类型、接口名称）
      interfaceInfo = await DebugApi.getApiInfo({
        id: data.config ? JSON.parse(data.config).source.parentId : data.parentId
      })
      caseInfo = await DebugApi.getCaseInfo({
        id: data.config ? JSON.parse(data.config).source.id : data.id
      })
    }
    // 新增页签并回显对应数据
    info.value =
      data.tag == '用例'
        ? {
            tag: data.tag,
            caseId: caseInfo.apiCasesReqVO.id,
            requestType: interfaceInfo.apiVO.requestType,
            url: interfaceInfo.apiVO.url,
            params: caseInfo.apiParamsReqVOS.find((c) => c.propertyType == 'params').propertyValue,
            body: caseInfo.apiParamsReqVOS.find((c) => c.propertyType == 'body').propertyValue,
            bodyForm: caseInfo.apiParamsReqVOS.find((c) => c.propertyType == 'bodyForm')
              .propertyValue,
            headers: caseInfo.apiParamsReqVOS.find((c) => c.propertyType == 'headers')
              .propertyValue,
            cookie: caseInfo.apiParamsReqVOS.find((c) => c.propertyType == 'cookie').propertyValue,
            auth: caseInfo.apiParamsReqVOS.find((c) => c.propertyType == 'auth').propertyValue,
            requestContentType: caseInfo.apiParamsReqVOS.find(
              (c) => c.propertyType == 'requestContentType'
            ).propertyValue,
            post: caseInfo.postProcessorResp
          }
        : {
            tag: '接口',
            requestType: interfaceInfo.apiVO.requestType,
            url: interfaceInfo.apiVO.url,
            params: interfaceInfo.apiRequestParamsVO.params,
            body: interfaceInfo.apiRequestParamsVO.body,
            bodyForm: interfaceInfo.apiRequestParamsVO.bodyForm,
            headers: interfaceInfo.apiRequestParamsVO.headers,
            cookie: interfaceInfo.apiRequestParamsVO.cookie,
            auth: interfaceInfo.apiRequestParamsVO.auth,
            requestContentType: interfaceInfo.apiVO.requestContentType,
            post: interfacePostList
          }
    response.value =
      data.tag == '用例'
        ? {
            responseContent: caseInfo.apiResponseReqVO.responseContent,
            responseHeaders: JSON.parse(caseInfo.apiResponseReqVO.responseHeader),
            responseResult: {
              requestUrl: caseInfo.apiResponseReqVO.requestUrl,
              responseResult: caseInfo.apiResponseReqVO.responseResult,
              responseCode: caseInfo.apiResponseReqVO.responseCode,
              responseTime: caseInfo.apiResponseReqVO.responseTime,
              responseSize: caseInfo.apiResponseReqVO.responseSize,
              responseContentType: caseInfo.apiResponseReqVO.responseContentType
            },
            requestHeaderList: JSON.parse(caseInfo.apiResponseReqVO.requestHeaderList),
            requestParamsList: JSON.parse(caseInfo.apiResponseReqVO.requestParamsList),
            requestBody: caseInfo.apiResponseReqVO.requestBody,
            imageUrl: caseInfo.apiResponseReqVO.imageUrl
          }
        : {}
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}
const handlePostData = (list) => {
  if (!list || !list.length) return []
  return list.map((item) => {
    return {
      stepId: item.stepId,
      type: item.type,
      status: item.status ? 0 : 1
    }
  })
}
/** 调试 */
const handleDebug = async () => {
  loading.value = true
  // 当前tab存储的请求信息
  try {
    let paramsValue = []
    if (
      ['form-data', 'x-www-form-urlencoded'].includes(queryInfo.value.requestContentType) &&
      queryInfo.value.bodyForm?.length
    ) {
      paramsValue = queryInfo.value.bodyForm || []
      paramsValue.forEach((item) => {
        if (isValidDateTime(item.keyValue)) {
          item.keyValue = encodeURI(item.keyValue)
        }
      })
    } else {
      paramsValue = queryInfo.value.params || []
      paramsValue.forEach((item) => {
        if (isValidDateTime(item.keyValue)) {
          item.keyValue = encodeURI(item.keyValue)
        }
      })
    }
    // headers处理 1.存在auth,Headers中有Authorization时进行替换，没有时进行添加2.不存在auth时，直接使用Headers
    let headers = [] as any
    if (queryInfo.value.auth) {
      if (!queryInfo.value.headers?.length) {
        headers = [
          {
            keyName: 'Authorization',
            keyValue: queryInfo.value.auth,
            keyType: 'string'
          }
        ]
      } else {
        const isHasAuthorization = queryInfo.value.headers.some((q) => q.keyName == 'Authorization')
        if (isHasAuthorization) {
          headers = queryInfo.value.headers.map((item) => {
            if (item.keyName == 'Authorization') {
              return {
                ...item,
                keyValue: queryInfo.value.auth,
                keyType: 'string'
              }
            }
            return item
          })
        } else {
          headers = [
            ...(queryInfo.value.headers || []),
            {
              keyName: 'Authorization',
              keyValue: queryInfo.value.auth,
              keyType: 'string'
            }
          ]
        }
      }
    } else {
      headers = [...(queryInfo.value.headers || [])]
    }
    const apiParams = {
      projectId: projectId.value,
      environmentId: environmentId.value,
      ...queryInfo.value.query,
      requestContentType: queryInfo.value.requestContentType || '',
      requestHeaderList: headers,
      requestParamsList: paramsValue,
      requestBodyList: [],
      requestBody: queryInfo.value.body || '',
      postProcessors: handlePostData(queryInfo.value.post)
    }
    let res = await DebugApi.apiDebug(apiParams)
    let {
      responseHeaders,
      responseContent,
      requestBody,
      requestHeaderList,
      requestParamsList,
      responseResult,
      responseCode,
      responseTime,
      responseSize,
      requestUrl,
      cookies,
      responseContentType,
      extractorResponse,
      assertInfos,
      imageUrl
    } = res
    /** 响应内容存储到对应tab */
    response.value = {
      requestHeaderList,
      requestBody,
      requestParamsList,
      responseHeaders,
      responseContent,
      extractorResponse,
      assertInfos,
      imageUrl,
      responseResult: {
        responseCode,
        responseTime,
        responseSize,
        responseResult,
        requestUrl,
        cookies,
        responseContentType
      }
    }
  } catch (error) {
    response.value = {
      requestHeaderList: [],
      requestBody: '',
      requestParamsList: [],
      responseHeaders: [],
      responseContent: '',
      extractorResponse: [],
      assertInfos: [],
      imageUrl: '',
      responseResult: {
        responseCode: '',
        responseTime: '',
        responseSize: '',
        responseResult: '',
        requestUrl: '',
        cookies: [],
        responseContentType: ''
      }
    }
  } finally {
    loading.value = false
  }
}
/** 请求form、参数等变化后，放到对应tab中 */
const handleQueryValue = (value) => {
  queryInfo.value = {
    query: value.query,
    requestContentType: value.requestContentType,
    params: value.params,
    bodyForm: value.bodyForm,
    body: value.json,
    headers: value.headers,
    auth: value.auth,
    cookie: value.cookies,
    post: value.post
  }
}
</script>

<style scoped>
:deep(.topBox) {
  padding-left: 10px;
}

:deep(.downBox) {
  padding-left: 10px;
}
</style>
